<?php


namespace app\admin\controller;


use app\common\model\NewsCategory;
use app\common\model\NewsCategoryModel;
use app\common\model\NewsModel;
use think\facade\Request;
use think\Validate;

class NewsController extends BaseController
{

    public function index()
    {
        $category = NewsCategoryModel::getList();
        $this->assign('category', $category);
        return $this->fetch();
    }

    public function getlist()
    {
        $all   = $this->getAllParams();
        $page  = Request::param("page");
        $limit = Request::param("limit");

        $where = [];

        if (isset($all['category_id'])) {
            $where[] = ['category_id', '=', "{$all['category_id']}"];
        }
        if (isset($all['is_banner'])) {
            $where[] = ['is_banner', '=', "{$all['is_banner']}"];
        }
        if (isset($all['is_hot'])) {
            $where[] = ['is_hot', '=', "{$all['is_hot']}"];
        }
        if (isset($all['title'])) {
            $where[] = ['title', 'like', "%{$all['title']}%"];
        }

        if (isset($all['start_time']) && $start_time = strtotime($all['start_time'])) {
            $where[] = ['publish_time', '>=', $start_time];
        }
        if (isset($all['end_time']) && $end_time = strtotime($all['end_time'])) {
            $where[] = ['publish_time', '<=', $end_time];
        }

        $field = 'id,author_name,title,left(content, 300) as content,publish_time,status,category_id,is_hot,is_banner, rand_hits';
        $list  = NewsModel::with([
            'category' => function ($query) {
                $query->where('id!=1')->field('id,category_name');
            }
        ])->where($where)
            ->field($field)
            ->order("publish_time desc")
            ->page($page, $limit)
            ->select();

        if (count($list)) {
            $count = NewsModel::where($where)->count("id");

            foreach ($list as &$item) {
                $item->author_name  = $item->author_name ?: '龙门小编';
                $item->publish_time = $item->publish_time > 0 ? date('Y-m-d H:i:s', $item->publish_time) : '';
                $item->content      = preg_replace('/<[^>]*(>)?/', '', $item->content);
                $item->content      = mb_substr($item->content, 0, 100);
            }

            return json(["code" => 0, "msg" => "", "data" => $list, "count" => $count]);
        }

        return self::bulidFail("未查询到相关数据");
    }

    public function add()
    {
        $category = NewsCategoryModel::getList();
        $this->assign('category', $category);
        return $this->fetch();
    }

    public function add_post()
    {
        $all_param = Request::param();
        $validate = new Validate([
            'title'       => 'require|length:2,128',
            'author_name' => 'require|length:2,20',
            'category_id' => 'require|number',
            'is_banner'   => 'require|in:0,1',
            // 'img'         => 'require|url',
            'is_hot'      => 'require|in:0,1',
            'status'      => 'require|in:0,1',
            'content'     => 'require',
        ], [
            "title"       => "标题在2-128个字符",
            "author_name" => "小编名称在2-20个字符",
            "category_id" => "请正确选择分类",
            "is_banner"   => "请正确选择是否轮播图",
            // "img"         => "请正确上传图片",
            "is_hot"      => "请正确选择是否热门",
            "status"      => "请正确选择状态",
            "content"     => "请输入内容",
        ]);
        if (!$validate->check($all_param)) {
            return self::bulidFail($validate->getError());
        }
        $news_model               = new NewsModel($all_param);
        $news_model->publish_time = time();
        $news_model->md5hash      = md5($news_model->title);
        // 查询标题是否存在
        if (NewsModel::where('title', $news_model->title)->field('id')->find()) {
            return self::bulidFail('标题已存在，请更换');
        }


        if ($news_model->save()) {
            // 记录日志
            $log_content = "添加资讯，ID：{$news_model->id}，标题：{$news_model->title}";
            parent::addAdminLog($log_content);

            return self::bulidSuccess();
        }
        return self::bulidFail();
    }

    public function edit()
    {
        $id = Request::param('id', 0, 'intval');
        if ($id < 1) {
            return $this->error('未查询到相关数据');
        }

        $info     = NewsModel::get($id);
        $category = NewsCategoryModel::getList();

        $this->assign('category', $category);
        $this->assign('info', $info);
        return $this->fetch();
    }

    public function edit_post()
    {
        $id        = Request::param('id', 0, 'intval');
        $all_param = Request::param();

        $validate = new Validate([
            'title'       => 'require|length:2,128',
            'author_name' => 'require|length:2,20',
            'category_id' => 'require|number',
            'is_banner'   => 'require|in:0,1',
            // 'img'         => 'require|url',
            'is_hot'      => 'require|in:0,1',
            'status'      => 'require|in:0,1',
            'content'     => 'require',
            // 'rand_hits'   => 'require'
        ], [
            "title"       => "标题在2-128个字符",
            "author_name" => "小编名称在2-20个字符",
            "category_id" => "请正确选择分类",
            "is_banner"   => "请正确选择是否轮播图",
            // "img"         => "请正确上传图片",
            "is_hot"      => "请正确选择是否热门",
            "status"      => "请正确选择状态",
            "content"     => "请输入内容",
            // 'rand_hits'   => '请填写阅读量'
        ]);

        if (!$validate->check($all_param)) {
            return self::bulidFail($validate->getError());
        }

        $news_info = NewsModel::get($id);
        if (empty($news_info)) {
            return self::bulidFail('帮助文档信息不存在');
        }

        // 查询标题是否已经存在
        $e_where = [
            ['id', '<>', $id],
            ['title', '=', $all_param['title']]
        ];
        $exists  = NewsModel::where($e_where)->field('id')->find();
        if (!empty($exists)) {
            return self::bulidFail('标题已经存在');
        }

        $news_info->title        = $all_param['title'];
        $news_info->content      = $all_param['content'];
        $news_info->status       = $all_param['status'];
        $news_info->is_hot       = $all_param['is_hot'];
        $news_info->is_banner    = $all_param['is_banner'];
        $news_info->img          = $all_param['img'];
        $news_info->author_name  = $all_param['author_name'];
        $news_info->category_id  = $all_param['category_id'];
        $news_info->rand_hits    = $all_param['rand_hits'];
        $news_info->publish_time = time();
        $news_info->md5hash      = md5($news_info->title);
        $news_info->own_creation = $all_param['own_creation'];

        if ($news_info->save()) {
            // 记录日志
            $log_content = "编辑资讯，ID：{$news_info->id}，标题：{$news_info->title}";
            parent::addAdminLog($log_content);

            return self::bulidSuccess();
        }
        return self::bulidFail();
    }

    public function del_post()
    {
        $id       = Request::param('id');
        $newsinfo = NewsModel::get($id);
        if (!$newsinfo) {
            return self::bulidFail('未查询到相关资讯');
        }

        if (NewsModel::where(['id' => $id])->delete()) {
            // 记录日志
            $log_content = "删除资讯，ID：{$newsinfo->id}，标题：{$newsinfo->title}";
            parent::addAdminLog($log_content);

            return self::bulidSuccess();
        }
        return self::bulidFail();
    }
}
